package com.zpz.framework.zpzoauth.config.oauth.authentication.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zpz.framework.zpzoauth.common.result.ZpzOauthResultMsg;
import com.zpz.framework.zpzoauth.common.result.ZpzOauthResultStatus;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangpanzhi
 * @time 2019-07-09
 * @description 未经本人允许请勿随便改动，尊重劳动
 * */
public class ZpzOauthAuthExceptionEntryPoint implements AuthenticationEntryPoint
{
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Throwable cause = authException.getCause();
        ZpzOauthResultMsg<Object> error = ZpzOauthResultMsg.error();
        if(cause instanceof InvalidTokenException) {
            if (authException.getMessage().contains("Access token expired:")){
                error=ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10038);
            }else{
                error=ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10042);
            }
        }else{
            error=ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10032);
        }
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), error);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}
